import Foundation
import StoreKit
extension Notification.Name {
    static let IAPValidateSuccessNotification = Notification.Name("IAPValidateSuccessNotification")
}
class AppProducts: NSObject {
    @objc static let shared = AppProducts()
    
    let yearFree = NSLocalizedString("xinguo_y", comment: "")
    let year = NSLocalizedString("boze_y1", comment: "")

    var ids: [String] {
        [yearFree]
    }
    var subscriptionExpirationDate: Date? {
        let dates = ids.compactMap { id in
            return UserDefaults.standard.object(forKey: id) as? Date
        }
        return dates.max()
    }
    lazy var store: IAPHelper = {
        return IAPHelper(productIds: Set(ids.map{$0}))
    }()
    @objc var isPurchased: Bool {
      let purchased = ids.map{store.isProductPurchased($0)}
//        return true
      return purchased.contains(true)
    }
    private override init() {
        super.init()
        NotificationCenter.default.addObserver(self, selector: #selector(self.startValidate), name: .IAPHelperPurchaseNotification, object: nil)
    }
}
extension AppProducts {
    @objc func startValidate(){
        if Receipt.isReceiptPresent() {
            validateReceipt()
        } else {
            refreshReceipt()
        }
    }
    @discardableResult
    func validateReceipt() -> Bool {
        let receipt = Receipt()
        guard let receiptStatus = receipt.receiptStatus,
              receiptStatus == .validationSuccess else {
            print("收据验证失败\(receipt.receiptStatus?.rawValue ?? "")")
            return false
        }
        let newestReceipt = receipt.inAppReceipts.filter { receipt in
            receipt.subscriptionExpirationDate != nil
        }.sorted { left, right in
            guard let leftDate = left.subscriptionExpirationDate,
                  let rightDate = right.subscriptionExpirationDate else {
                      return false
                  }
            return leftDate > rightDate
        }.first
        guard let inAppReceipt =  newestReceipt,
              let productIdentifier = inAppReceipt.productIdentifier else {
            return false
        }
        guard let date = inAppReceipt.subscriptionExpirationDate else {
            return false
        }
        if date > Date() {
            UserDefaults.standard.set(date, forKey: productIdentifier)
            store.purchasedProductIdentifiers.insert(productIdentifier)
            NotificationCenter.default.post(name: .IAPValidateSuccessNotification, object: nil)
            return true
        }
        store.purchasedProductIdentifiers.remove(productIdentifier)
        UserDefaults.standard.removeObject(forKey: productIdentifier)
        return false
    }
    func refreshReceipt() {
        print("Requesting refresh of receipt.")
        let refreshRequest = SKReceiptRefreshRequest()
        refreshRequest.delegate = self
        refreshRequest.start()
    }
}
extension AppProducts: SKRequestDelegate {
    public func requestDidFinish(_ request: SKRequest) {
        if Receipt.isReceiptPresent() {
            print("Verifying newly refreshed receipt.")
            validateReceipt()
        }
    }
    func request(_ request: SKRequest, didFailWithError error: Error) {
        print("StoreKit request failed: \(error.localizedDescription)")
    }
}
